package com.yu.newsSys.listener;

import com.yu.newsSys.constants.ListenerConstants;
import com.yu.newsSys.constants.SessionConstants;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.List;
@WebListener
public class OnlineHttpSessionListener implements HttpSessionListener {
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        String userAttribute = (String) session.getAttribute(SessionConstants.USER_SESSION);
        if (userAttribute != null) {
            // 如果当前session中有着user这样一个attribute则清除servletContext中的对应属性
            ServletContext context = session.getServletContext();
            List<String> onlineList = (List<String>) context.getAttribute(ListenerConstants.ONLINE_LIST);
            onlineList.remove(userAttribute);
        }
    }
}
